import { AppoxAudioSample } from '@/appox/appox'

class AudioPlayer {
  constructor() {
    this.audioContext = null;
    this.sampleRate = 44100; // 默认采样率
    this.channels = 1; // 单声道
    this.bufferSize = 2048; // 缓冲区大小
    this.scriptNode = null;
    this.audioBuffer = [];
    this.bufferIndex = 0;
    this.isInitialized = false;
    this.maxBufferSize = 44100 * 2; // 最大缓冲区大小（2秒音频）
  }

  async onStartSession() {
    if (this.isInitialized) return;
    
    try {
      // 如果 audioContext 不存在或已关闭，则创建新的
      if (!this.audioContext || this.audioContext.state === 'closed') {
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
      }
      
      if (this.audioContext.state === 'suspended') {
        await this.audioContext.resume();
      }

      this.scriptNode = this.audioContext.createScriptProcessor(this.bufferSize, 0, this.channels);
      this.scriptNode.onaudioprocess = (event) => this.onAudioProcess(event);
      this.scriptNode.connect(this.audioContext.destination);
      
      this.isInitialized = true;
    } catch (error) {
      console.error('音频播放器初始化失败:', error);
    }
  }

  onStopSession() {
    if (this.scriptNode) {
      this.scriptNode.disconnect();
      this.scriptNode = null;
    }
    this.audioBuffer = [];
    this.bufferIndex = 0;
    this.isInitialized = false;
  }

  onInputData(data) {
    if (data && data instanceof AppoxAudioSample) {
      if (!this.isInitialized || !data.data) return;

      try {
        const floatData = new Float32Array(data.data.length);
        for (let i = 0; i < data.data.length; i++) {
          floatData[i] = data.data[i] / 32768.0;
        }

        this.audioBuffer.push(...floatData);
        
        if (this.audioBuffer.length > this.maxBufferSize) {
          const excess = this.audioBuffer.length - this.maxBufferSize;
          this.audioBuffer.splice(0, excess);
          this.bufferIndex = Math.max(0, this.bufferIndex - excess);
        }
        
      } catch (error) {
        console.error('添加音频数据失败:', error);
      }
    }
  }

  onAudioProcess(event) {
    const outputBuffer = event.outputBuffer;
    const channelData = outputBuffer.getChannelData(0);

    for (let i = 0; i < channelData.length; i++) {
      if (this.bufferIndex < this.audioBuffer.length) {
        channelData[i] = this.audioBuffer[this.bufferIndex++];
      } else {
        channelData[i] = 0; // 静音
      }
    }

    if (this.bufferIndex > this.maxBufferSize) {
      this.audioBuffer.splice(0, this.bufferIndex);
      this.bufferIndex = 0;
    }
  }
}

const audioPlayer = new AudioPlayer();
export default audioPlayer; 